<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="模板管理">
        管理系统文档模板，包括签到表模板和评审费发放单模板。
      </n-card>
    </div>
    
    <n-tabs type="line" animated>
      <n-tab-pane name="signin" tab="签到表模板">
        <n-card :bordered="false" title="签到表模板列表" class="mt-4">
          <template #header-extra>
            <n-space>
              <n-button type="primary" @click="handleAddSignin">
                <template #icon>
                  <n-icon>
                    <AddOutline />
                  </n-icon>
                </template>
                上传模板
              </n-button>
              <n-button @click="handleRefreshSignin">
                <template #icon>
                  <n-icon>
                    <RefreshOutline />
                  </n-icon>
                </template>
                刷新
              </n-button>
            </n-space>
          </template>

          <n-data-table
            :columns="signinColumns"
            :data="signinTableData"
            :pagination="signinPagination"
            :loading="signinLoading"
            :bordered="false"
            striped
          />
        </n-card>
      </n-tab-pane>

      <n-tab-pane name="payment" tab="评审费发放单模板">
        <n-card :bordered="false" title="评审费发放单模板列表" class="mt-4">
          <template #header-extra>
            <n-space>
              <n-button type="primary" @click="handleAddPayment">
                <template #icon>
                  <n-icon>
                    <AddOutline />
                  </n-icon>
                </template>
                上传模板
              </n-button>
              <n-button @click="handleRefreshPayment">
                <template #icon>
                  <n-icon>
                    <RefreshOutline />
                  </n-icon>
                </template>
                刷新
              </n-button>
            </n-space>
          </template>

          <n-data-table
            :columns="paymentColumns"
            :data="paymentTableData"
            :pagination="paymentPagination"
            :loading="paymentLoading"
            :bordered="false"
            striped
          />
        </n-card>
      </n-tab-pane>
    </n-tabs>

    <!-- 上传签到表模板对话框 -->
    <n-modal v-model:show="showSigninModal" :show-mask="true" preset="dialog" title="上传签到表模板">
      <n-form
        ref="signinFormRef"
        :model="signinFormData"
        :rules="signinRules"
        label-placement="left"
        :label-width="100"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="模板名称" path="name">
          <n-input v-model:value="signinFormData.name" placeholder="请输入模板名称" />
        </n-form-item>
        <n-form-item label="模板描述" path="description">
          <n-input
            v-model:value="signinFormData.description"
            type="textarea"
            placeholder="请输入模板描述"
            :rows="3"
          />
        </n-form-item>
        <n-form-item label="模板文件" path="file">
          <n-upload
            v-model:file-list="signinFormData.fileList"
            :max="1"
            accept=".doc,.docx"
            :show-file-list="true"
            :show-preview-button="false"
            :show-remove-button="true"
            :show-download-button="false"
          >
            <n-button>选择文件</n-button>
            <template #tip>
              <div>支持 .doc 和 .docx 格式，文件大小不超过 10MB</div>
            </template>
          </n-upload>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="signinFormData.status" />
          <span class="ml-2">{{ signinFormData.status ? '启用' : '禁用' }}</span>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showSigninModal = false">取消</n-button>
          <n-button type="primary" :loading="signinSubmitLoading" @click="handleSigninSubmit">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 上传评审费发放单模板对话框 -->
    <n-modal v-model:show="showPaymentModal" :show-mask="true" preset="dialog" title="上传评审费发放单模板">
      <n-form
        ref="paymentFormRef"
        :model="paymentFormData"
        :rules="paymentRules"
        label-placement="left"
        :label-width="100"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="模板名称" path="name">
          <n-input v-model:value="paymentFormData.name" placeholder="请输入模板名称" />
        </n-form-item>
        <n-form-item label="模板描述" path="description">
          <n-input
            v-model:value="paymentFormData.description"
            type="textarea"
            placeholder="请输入模板描述"
            :rows="3"
          />
        </n-form-item>
        <n-form-item label="模板文件" path="file">
          <n-upload
            v-model:file-list="paymentFormData.fileList"
            :max="1"
            accept=".doc,.docx"
            :show-file-list="true"
            :show-preview-button="false"
            :show-remove-button="true"
            :show-download-button="false"
          >
            <n-button>选择文件</n-button>
            <template #tip>
              <div>支持 .doc 和 .docx 格式，文件大小不超过 10MB</div>
            </template>
          </n-upload>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="paymentFormData.status" />
          <span class="ml-2">{{ paymentFormData.status ? '启用' : '禁用' }}</span>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showPaymentModal = false">取消</n-button>
          <n-button type="primary" :loading="paymentSubmitLoading" @click="handlePaymentSubmit">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog, NSwitch } from 'naive-ui';
import {
  AddOutline,
  RefreshOutline,
  CreateOutline,
  TrashOutline,
  DownloadOutline,
  EyeOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

const message = useMessage();
const dialog = useDialog();

// 签到表模板相关
const signinLoading = ref(false);
const signinTableData = ref<any[]>([]);
const signinPagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageCount: 1,
  onChange: (page: number) => {
    signinPagination.page = page;
    loadSigninData();
  },
  onUpdatePageSize: (pageSize: number) => {
    signinPagination.pageSize = pageSize;
    signinPagination.page = 1;
    loadSigninData();
  },
});

const signinColumns = computed(() => [
  createIndexColumn({
    currentPage: signinPagination.page,
    pageSize: signinPagination.pageSize,
  }),
  {
    title: '模板名称',
    key: 'name',
    width: 200,
  },
  {
    title: '模板描述',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '文件大小',
    key: 'fileSize',
    width: 120,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
        h(NSwitch, {
          value: row.status === true,
          onUpdateValue: (value: boolean) => {
            // 更新数据中的状态
            row.status = value;
            console.log('状态切换:', row.id, value);
          }
        }),
        h('span', { style: 'font-size: 12px;' }, row.status ? '启用' : '禁用')
      ]);
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row: any) => h('div', { style: 'display: flex; align-items: center; gap: 12px;' }, [
      h('n-button', {
        size: 'small',
        onClick: () => handlePreviewSignin(row),
      }, {
        icon: () => h('n-icon', {}, h(EyeOutline)),
        default: () => '预览',
      }),
      h('n-button', {
        size: 'small',
        onClick: () => handleDownloadSignin(row),
      }, {
        icon: () => h('n-icon', {}, h(DownloadOutline)),
        default: () => '下载',
      }),
      h('n-button', {
        size: 'small',
        type: 'error',
        onClick: () => handleDeleteSignin(row),
      }, {
        icon: () => h('n-icon', {}, h(TrashOutline)),
        default: () => '删除',
      }),
    ]),
  },
]);

// 评审费发放单模板相关
const paymentLoading = ref(false);
const paymentTableData = ref<any[]>([]);
const paymentPagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageCount: 1,
  onChange: (page: number) => {
    paymentPagination.page = page;
    loadPaymentData();
  },
  onUpdatePageSize: (pageSize: number) => {
    paymentPagination.pageSize = pageSize;
    paymentPagination.page = 1;
    loadPaymentData();
  },
});

const paymentColumns = computed(() => [
  createIndexColumn({
    currentPage: paymentPagination.page,
    pageSize: paymentPagination.pageSize,
  }),
  {
    title: '模板名称',
    key: 'name',
    width: 200,
  },
  {
    title: '模板描述',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '文件大小',
    key: 'fileSize',
    width: 120,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
        h(NSwitch, {
          value: row.status === true,
          onUpdateValue: (value: boolean) => {
            // 更新数据中的状态
            row.status = value;
            console.log('状态切换:', row.id, value);
          }
        }),
        h('span', { style: 'font-size: 12px;' }, row.status ? '启用' : '禁用')
      ]);
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row: any) => h('div', { style: 'display: flex; align-items: center; gap: 12px;' }, [
      h('n-button', {
        size: 'small',
        onClick: () => handlePreviewPayment(row),
      }, {
        icon: () => h('n-icon', {}, h(EyeOutline)),
        default: () => '预览',
      }),
      h('n-button', {
        size: 'small',
        onClick: () => handleDownloadPayment(row),
      }, {
        icon: () => h('n-icon', {}, h(DownloadOutline)),
        default: () => '下载',
      }),
      h('n-button', {
        size: 'small',
        type: 'error',
        onClick: () => handleDeletePayment(row),
      }, {
        icon: () => h('n-icon', {}, h(TrashOutline)),
        default: () => '删除',
      }),
    ]),
  },
]);

// 签到表模板表单
const showSigninModal = ref(false);
const signinSubmitLoading = ref(false);
const signinFormRef = ref();
const signinFormData = reactive({
  id: '',
  name: '',
  description: '',
  fileList: [],
  status: true,
});

const signinRules = {
  name: {
    required: true,
    message: '请输入模板名称',
    trigger: 'blur',
  },
  description: {
    required: true,
    message: '请输入模板描述',
    trigger: 'blur',
  },
};

// 评审费发放单模板表单
const showPaymentModal = ref(false);
const paymentSubmitLoading = ref(false);
const paymentFormRef = ref();
const paymentFormData = reactive({
  id: '',
  name: '',
  description: '',
  fileList: [],
  status: true,
});

const paymentRules = {
  name: {
    required: true,
    message: '请输入模板名称',
    trigger: 'blur',
  },
  description: {
    required: true,
    message: '请输入模板描述',
    trigger: 'blur',
  },
};

// 加载签到表模板数据
const loadSigninData = async () => {
  signinLoading.value = true;
  try {
    // 模拟数据
    signinTableData.value = [
      {
        id: '1',
        name: '标准签到表模板',
        description: '包含姓名、部职别、时间等字段的标准签到表模板',
        fileSize: '2.5MB',
        status: true,
        createTime: '2024-01-15 10:30:00',
      },
      {
        id: '2',
        name: '简化签到表模板',
        description: '简化版签到表模板，适用于小型会议',
        fileSize: '1.8MB',
        status: false,
        createTime: '2024-01-10 14:20:00',
      },
    ];
  } catch (error) {
    message.error('加载数据失败');
  } finally {
    signinLoading.value = false;
  }
};

// 加载评审费发放单模板数据
const loadPaymentData = async () => {
  paymentLoading.value = true;
  try {
    // 模拟数据
    paymentTableData.value = [
      {
        id: '1',
        name: '标准评审费发放单模板',
        description: '包含专家信息、金额、银行账号等字段的完整发放单模板',
        fileSize: '3.2MB',
        status: true,
        createTime: '2024-01-15 10:30:00',
      },
      {
        id: '2',
        name: '简化评审费发放单模板',
        description: '简化版发放单模板，适用于特殊情况',
        fileSize: '2.1MB',
        status: true,
        createTime: '2024-01-12 09:15:00',
      },
    ];
  } catch (error) {
    message.error('加载数据失败');
  } finally {
    paymentLoading.value = false;
  }
};

// 签到表模板操作
const handleRefreshSignin = () => {
  loadSigninData();
};

const handleAddSignin = () => {
  Object.assign(signinFormData, {
    id: '',
    name: '',
    description: '',
    fileList: [],
    status: true,
  });
  showSigninModal.value = true;
};

const handleSigninSubmit = async () => {
  try {
    await signinFormRef.value?.validate();
    signinSubmitLoading.value = true;
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    message.success(signinFormData.id ? '修改成功' : '上传成功');
    showSigninModal.value = false;
    loadSigninData();
  } catch (error) {
    message.error('操作失败');
  } finally {
    signinSubmitLoading.value = false;
  }
};

const handlePreviewSignin = (row: any) => {
  message.info(`预览模板：${row.name}`);
};

const handleDownloadSignin = (row: any) => {
  message.success(`下载模板：${row.name}`);
};

const handleDeleteSignin = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除模板"${row.name}"吗？此操作不可恢复。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
        message.success('删除成功');
        loadSigninData();
      } catch (error) {
        message.error('删除失败');
      }
    },
  });
};

// 评审费发放单模板操作
const handleRefreshPayment = () => {
  loadPaymentData();
};

const handleAddPayment = () => {
  Object.assign(paymentFormData, {
    id: '',
    name: '',
    description: '',
    fileList: [],
    status: true,
  });
  showPaymentModal.value = true;
};

const handlePaymentSubmit = async () => {
  try {
    await paymentFormRef.value?.validate();
    paymentSubmitLoading.value = true;
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    message.success(paymentFormData.id ? '修改成功' : '上传成功');
    showPaymentModal.value = false;
    loadPaymentData();
  } catch (error) {
    message.error('操作失败');
  } finally {
    paymentSubmitLoading.value = false;
  }
};

const handlePreviewPayment = (row: any) => {
  message.info(`预览模板：${row.name}`);
};

const handleDownloadPayment = (row: any) => {
  message.success(`下载模板：${row.name}`);
};

const handleDeletePayment = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除模板"${row.name}"吗？此操作不可恢复。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
        message.success('删除成功');
        loadPaymentData();
      } catch (error) {
        message.error('删除失败');
      }
    },
  });
};

onMounted(() => {
  loadSigninData();
  loadPaymentData();
});
</script>

<style scoped>
.n-layout-page-header {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
</style> 